/**
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 */
package com.jeesite.modules.wx.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jeesite.common.collect.ListUtils;
import com.jeesite.common.collect.MapUtils;
import com.jeesite.common.lang.StringUtils;
import com.jeesite.modules.common.refun.CollectionUtil;
import com.jeesite.modules.common.refun.StringUtil;
import com.jeesite.modules.sys.entity.Office;
import com.jeesite.modules.sys.entity.User;
import com.jeesite.modules.test.entity.TestTree;
import com.jeesite.modules.test.service.TestTreeService;
import com.jeesite.modules.wx.entity.WxBusiness;
import com.jeesite.modules.wx.entity.WxUser;
import com.jeesite.modules.wx.service.WxBusinessService;
import com.jeesite.modules.wx.service.WxUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import com.jeesite.common.config.Global;
import com.jeesite.common.entity.Page;
import com.jeesite.common.web.BaseController;
import com.jeesite.modules.wx.entity.WxBusinessUser;
import com.jeesite.modules.wx.service.WxBusinessUserService;

import java.awt.datatransfer.Transferable;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * wx_business_userController
 * @author wangjianxin
 * @version 2018-11-13
 */
@Controller
@RequestMapping(value = "${adminPath}/wx/wxBusinessUser")
@Slf4j
public class WxBusinessUserController extends BaseController {

	@Autowired
	private WxBusinessUserService wxBusinessUserService;
	@Autowired
	private WxBusinessService wxBusinessService;
	@Autowired
	private WxUserService wxUserService;
	@Autowired
	private TestTreeService testTreeService;
//
//	/**
//	 * 获取数据
//	 */
//	@ModelAttribute
//	public WxBusinessUser get(String id, boolean isNewRecord) {
//		return wxBusinessUserService.get(id, isNewRecord);
//	}
	
	/**
	 * 查询列表
	 */
	@RequiresPermissions("wx:wxBusinessUser:view")
	@RequestMapping(value = {"list", ""})
	public String list(WxBusinessUser wxBusinessUser, Model model,@RequestParam(value = "businessId",required = false) String businessId){
		model.addAttribute("wxBusinessUser", wxBusinessUser);
		model.addAttribute("businessId", businessId);
		return "modules/wx/wxBusinessUserList";
	}
	
	/**
	 * 查询列表数据
	 */
	@RequiresPermissions("wx:wxBusinessUser:view")
	@RequestMapping(value = "listData")
	@ResponseBody
	public Page<WxBusinessUser> listData(WxBusinessUser wxBusinessUser, HttpServletRequest request, HttpServletResponse response,
										 @RequestParam(value = "businessId",required = false) String businessId) {
		String businessName = "";
		Page<WxBusinessUser> page = wxBusinessUserService.findPage(new Page<WxBusinessUser>(request, response), wxBusinessUser);
		for(WxBusinessUser temp : page.getList()){

			Long id = temp.getBusinessId();
			WxBusiness wxBusiness = wxBusinessService.get(id.toString());
			temp.setBusinessName(wxBusiness.getName());

			Long userId = temp.getUserId();
			WxUser wxUser = wxUserService.get(userId.toString());
			temp.setNickName(wxUser.getNickName());
		}

		if(StringUtil.isNotEmpty(businessName)){
			page.setPageInfo(businessName);
		}
		return page;
	}

	/**
	 * 查看编辑表单
	 */
	@RequiresPermissions("wx:wxBusinessUser:view")
	@RequestMapping(value = "form")
	public String form(WxBusinessUser wxBusinessUser, Model model,
					   @RequestParam(value = "activityId",required = false) String activityId) {
		Long businessId  = wxBusinessUser.getBusinessId();
		if(null != businessId){
			WxBusiness wxBusiness = wxBusinessService.get(businessId.toString());
			model.addAttribute("wxBusiness", wxBusiness);
		}
		model.addAttribute("wxBusinessUser", wxBusinessUser);
		model.addAttribute("activityId", activityId);
		return "modules/wx/wxBusinessUserForm";
	}

	/**
	 * 保存wx_business_user
	 */
	@RequiresPermissions("wx:wxBusinessUser:edit")
	@PostMapping(value = "save")
	@ResponseBody
	public String save(@Validated WxBusinessUser wxBusinessUser) {
		wxBusinessUserService.save(wxBusinessUser);
		return renderResult(Global.TRUE, text("保存wx_business_user成功！"));
	}
	/**
	 * 保存wx_business_user
	 */
	@PostMapping(value = "saveBusinessUser")
	@ResponseBody
	public String saveBusinessUser(@Validated WxBusinessUser wxBusinessUser) {
		Long businessId = wxBusinessUser.getBusinessId();
		//wxBusinessUser中WxUser的id是id+nickName，例如选择了3个人，这里的字符串分割后前三个都是id后三个都是对于的nickName
		String ids = wxBusinessUser.getWxUser().getId();
		String[] idAndNickName = ids.split(",");
		int len = idAndNickName.length;

		String[] w = new String[len/2];

		//参数：数组源，拷贝的起始下标，目标数组，填写的起始下标，拷贝的长度）
		System.arraycopy(idAndNickName, 0, w, 0, len/2);

		log.info("获得选择员工的id数组={}",Arrays.toString(w));
		int wlen = w.length;
		for(int i = 0;i<wlen;i++){
			String saveUserId = w[i];
			//检查用户id是否正确
			WxUser wxUser = wxUserService.get(saveUserId);
			if(null != wxUser){
				WxBusinessUser saveBusinessUser = new WxBusinessUser();
				//员工id
				saveBusinessUser.setUserId(Long.valueOf(saveUserId));
				//检查是否添加过
				List<WxBusinessUser> wxBusinessUserList = wxBusinessUserService.findList(saveBusinessUser);
				if(CollectionUtil.isNotEmpty(wxBusinessUserList)){
					log.error("添加员工失败={}",saveUserId);
					return renderResult(Global.FALSE, text("添加失败，用户【"+wxUser.getNickName()+"】已经被添加"));
				}
				//商家id
				saveBusinessUser.setBusinessId(businessId);
				saveBusinessUser.setUserName(wxUser.getUserName());

				saveBusinessUser.setPhone(wxUser.getPhone());
				wxBusinessUserService.save(saveBusinessUser);
			}else{
				throw new RuntimeException("用户不存在");
			}
		}

		return renderResult(Global.TRUE, text("保存员工成功！"));
	}
	
	/**
	 * 删除wx_business_user
	 */
	@RequiresPermissions("wx:wxBusinessUser:edit")
	@RequestMapping(value = "delete")
	@ResponseBody
	public String delete(WxBusinessUser wxBusinessUser) {
		wxBusinessUserService.delete(wxBusinessUser);
		return renderResult(Global.TRUE, text("删除wx_business_user成功！"));
	}

	/**
	 * 查询商家员工，需要购买过活动的
	 * @return
	 */
	@RequestMapping("/treeData")
	@ResponseBody
	public List<Map<String, Object>> treeData(@RequestParam(value = "activityId",required = false) String activityId){
		List<Map<String, Object>> mapList = ListUtils.newArrayList();
		if(StringUtil.isEmpty(activityId)){
			return mapList;
		}
		List<WxUser> wxUserList = wxUserService.treeDataForBuyActivity(activityId);
		for(WxUser temp: wxUserList){
			Map<String, Object> map = MapUtils.newHashMap();

			// 过滤非正常的数据
			if (!TestTree.STATUS_NORMAL.equals(temp.getStatus())){
				continue;
			}

			//排除已经存在的员工
//			WxBusinessUser wxBusinessUser = new WxBusinessUser();
//			wxBusinessUser.setUserId(Long.valueOf(temp.getId()));
//			List<WxBusinessUser> wxBusinessUserList = wxBusinessUserService.findList(wxBusinessUser);
//			if(CollectionUtil.isNotEmpty(wxBusinessUserList)){
//				continue;
//			}

			map.put("id", temp.getId());
//			map.put("name", StringUtils.getTreeNodeName("null", temp.getId(), temp.getNickName()));
			map.put("name", temp.getNickName()+","+temp.getPhone());
			mapList.add(map);

		}

		return mapList;
	}

//
//	@RequiresPermissions({"user"})
//	@RequestMapping({"treeData"})
//	@ResponseBody
//	public List<Map<String, Object>> treeData(String excludeCode, String parentCode, Boolean isAll, String officeTypes, String companyCode, String isShowCode, String isShowFullName, Boolean isLoadUser, String postCode, String roleCode, String ctrlPermi) {
//		List<Map<String, Object>> mapList = ListUtils.newArrayList();
//		Office where = new Office();
//		where.setStatus("0");
//		where.setCompanyCode(companyCode);
//		if (isAll == null || !isAll) {
//			this.officeService.addDataScopeFilter(where, (String) StringUtils.defaultIfBlank(ctrlPermi, "1"));
//		}
//
//		List<Office> list = this.officeService.findList(where);
//
//		for(int i = 0; i < list.size(); ++i) {
//			Office e = (Office)list.get(i);
//			if ("0".equals(e.getStatus()) && (!StringUtils.isNotBlank(excludeCode) || !e.getId().equals(excludeCode) && !e.getParentCodes().contains("," + excludeCode + ",")) && (!StringUtils.isNotBlank(parentCode) || e.getOfficeCode().equals(parentCode) && e.getParentCodes().contains("," + parentCode + ",")) && (!StringUtils.isNotBlank(officeTypes) || StringUtils.inString(e.getOfficeType(), officeTypes.split(",")))) {
//				Map<String, Object> map = MapUtils.newHashMap();
//				map.put("id", e.getId());
//				map.put("pId", e.getParentCode());
//				String name = e.getOfficeName();
//				if ("true".equals(isShowFullName) || "1".equals(isShowFullName)) {
//					name = e.getFullName();
//				}
//
//				map.put("name", StringUtils.getTreeNodeName(isShowCode, e.getViewCode(), name));
//				map.put("title", e.getFullName());
//				if (isLoadUser != null && isLoadUser) {
//					map.put("isParent", true);
//					List<Map<String, Object>> userList = this.empUserController.treeData("u_", e.getOfficeCode(), e.getOfficeCode(), companyCode, postCode, roleCode, isAll, isShowCode);
//					mapList.addAll(userList);
//				}
//
//				mapList.add(map);
//			}
//		}
//
//		return mapList;
//	}
}